<script setup lang='ts'>
import type { IAdd, IEdit, IList } from '@fl/api/joint-api/model/fscat-model'
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

import { fscatAdd, fscatDelete, fscatEdit, fscatList } from '@fl/api/joint-api/index'

import EditForm from './edit-form.vue'
import { useAreaData } from '@/hooks/useAreaList'

const formTypeEunm = {
    add: '新建',
    destroy: '删除',
    edit: '编辑',
} as const

type RowVO = {
    apply: string
    customer: string
    name: string
    num: string
    typeName: string
}
const state = ref({
    apply: '',
    customer: '',
    id: '',
    img: '',
    info: '',
    name: '',
    type: null,
    userType: '',
    cityCode: '',
    areaCode: '',
})
const { areaList } = useAreaData()

const centerDialogVisible = ref(false)
const formType = ref('')
const dialogTitle = computed(() => {
    return `${formType.value}产品分类`
})
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const xGrid = ref<VxeGridInstance<RowVO>>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { title: '序号', type: 'seq', width: 50 },
        { field: 'name', title: '分类名称' },
        { field: 'typeName', title: '类别' },
        { field: 'num', title: '产品数' },
        { field: 'customer', title: '目标客户' },
        { field: 'apply', title: '申请条件' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },

    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: '520',
    keepSource: true,
    loading: false,
    showOverflow: true,
})
const submitLoading = ref(false)
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}

async function findList() {
    gridOptions.loading = true
    try {
        const params: IList = {
            page: tablePage.currentPage,
            size: tablePage.pageSize,
            sort: 'create_time,desc',
        }
        const data = await fscatList(params)
        gridOptions.loading = false
        gridOptions.data = data.records
        tablePage.total = data.total
    }
    catch (error) {
        gridOptions.loading = false
    }
}
findList()
function resetFormParams() {
    submitLoading.value = false
    state.value = {
        apply: '',
        customer: '',
        id: '',
        img: '',
        info: '',
        name: '',
        type: null,
        userType: '',
        cityCode: '',
        areaCode: '',
    }
}
function showForm(type: string, row?: any) {
    formType.value = type
    if (formType.value === formTypeEunm.edit) {
        console.log(row)
        state.value = {
            apply: row.apply,
            customer: row.customer,
            id: row.id,
            img: row.img,
            info: row.info,
            name: row.name,
            type: row.type,
            userType: String(row.userType),
            cityCode: row?.cityCode ? `${row?.cityCode}-${row?.cityName || ''}` : '',
            areaCode: row?.areaCode ? `${row?.areaCode}-${row?.areaName || ''}` : '',
        }
    }
    centerDialogVisible.value = true
}
async function formSubmit() {
    if (formType.value === formTypeEunm.add)
        addData()

    if (formType.value === formTypeEunm.edit)
        editData()
}
async function deleteRow(row: any) {
    console.log(row)
    try {
        await fscatDelete(row.id)
        ElMessage.success('删除成功')
        findList()
    }
    catch (error) {

    }
}

async function addData() {
    submitLoading.value = true
    try {
        const params: IAdd = {
            apply: state.value.apply,
            customer: state.value.customer,
            img: state.value.img,
            info: state.value.info,
            isDeleted: 0,
            name: state.value.name,
            status: 1,
            type: state.value.type ?? 0,
            userType: Number(state.value.userType),
            cityCode: state.value.cityCode?.split('-')[0] || '',
            cityName: state.value.cityCode?.split('-')[1] || '',
            areaCode: state.value.areaCode?.split('-')[0] || '',
            areaName: state.value.areaCode?.split('-')[1] || '',
        }
        const data = await fscatAdd(params)
        if (data === 1)
            ElMessage.success('添加成功')
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
async function editData() {
    submitLoading.value = true
    try {
        const params: IEdit = {
            apply: state.value.apply,
            customer: state.value.customer,
            id: state.value.id,
            img: state.value.img,
            info: state.value.info,
            isDeleted: 0,
            name: state.value.name,
            status: 1,
            type: state.value.type ?? 0,
            userType: Number(state.value.userType),
            cityCode: state.value.cityCode?.split('-')[0] || '',
            cityName: state.value.cityCode?.split('-')[1] || '',
            areaCode: state.value.areaCode?.split('-')[0] || '',
            areaName: state.value.areaCode?.split('-')[1] || '',
        }
        const data = await fscatEdit(params)
        if (data === 1)
            ElMessage.success('修改成功')
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
function updateloading(val: boolean) {
    submitLoading.value = val
}
</script>

<template>
    <div class="p-30 bg-white">
        <div class="mb-20">
            <ElButton type="primary"
                      @click="showForm(formTypeEunm.add)"
            >
                {{ formTypeEunm.add }}
            </ElButton>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
                  :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
        >
            <template #operate="{ row }">
                <ElButton @click="showForm(formTypeEunm.edit, row)">
                    {{ formTypeEunm.edit }}
                </ElButton>

                <ElButton @click="deleteRow(row)">
                    {{ formTypeEunm.destroy }}
                </ElButton>
            </template>

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="dialogTitle"
               width="800"
               destroy-on-close
               align-center
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <div class="pb-10 max-h-750 of-auto">
            <EditForm :state="state"
                      :loading="submitLoading"
                      :areaList="areaList"
                      @close="centerDialogVisible = false"
                      @submit="formSubmit"
                      @updateloading="updateloading"
            />
        </div>
    </el-dialog>
</template>
